# -*- coding:utf-8 -*-
#作者：琴弦上的宇宙
#时间：2021年10月22日

import os
from math import *
from common import *
from openCv import *

class scFightBox(myScene):
    def __init__(self,bValid):
        self.bValid=bValid
        self.name='scFightBox'
        self.path='resource/mercenary/base/scFightBox'
        self.tagPng=[myPng(self.path,png) for png in os.listdir(self.path) if png.startswith('tag')]
        self.funcPng=[myPng(self.path,png) for png in os.listdir(self.path) if png.startswith('func')]

    def enable(self):
        self.bValid=True

    def dis(self):
        self.bValid=False

    def isOwn(self,background):
        if self.bValid:
            tagList={}
            for tag in self.tagPng:
                bFind,x,y,w,h=bFindInBackground(background,tag,0.70)
                if bFind:
                    tagList[tag.name]=(x,y,w,h)
                    break
            if ('tagBox1' in tagList) or \
               ('tagBox2' in tagList) or \
               ('tagBox3' in tagList) or \
               ('tagBox4' in tagList) or \
               ('tagBox5' in tagList) or \
               ('tagPass1' in tagList) or \
               ('tagPass2' in tagList) or \
               ('tagPass3' in tagList):
                return True
            else:
                return False
        else:
            return False

    def proc(self,background):

        #循环
        bg=background
        while True:

            #开宝箱
            allList=[]
            for func in self.funcPng:
                if (func.name=='funcBox1') or (func.name=='funcBox2') or \
                    (func.name=='funcBox3') or (func.name=='funcBox4') or \
                    (func.name=='funcBox5'):
                    bFind,okList=bFindMultInBackground(bg,func,0.70)
                    if bFind:
                        for pos in okList:
                            allList.append(pos)
            if len(allList)>0:
                allList.sort()
                curr=allList[0]
                moveAndClick(curr[0]+curr[2]/2,curr[1]+curr[3]/2,0)
                for pos in allList:
                    if not ((abs(pos[0]-curr[0])<10)and(abs(pos[1]-curr[1])<10)):
                        curr=pos
                        moveAndClick(curr[0]+curr[2]/2,curr[1]+curr[3]/2,0)

            #开完宝箱
            time.sleep(1)
            bg=SaveScreen()
            for func in self.funcPng:
                if (func.name=='funcPass1') or \
                    (func.name=='funcPass2') or \
                    (func.name=='funcPass3'):
                    bFind,x,y,w,h=bFindInBackground(bg,func,0.70)
                    if bFind:
                        SaveAwardPng()
                        moveAndClick(x+w/2,y+h/2,5)
                        return True

            #重新截图判断
            bg=SaveScreen()
            if not self.isOwn(bg):
                return False
